package com.heaven.jane.sourcegenerator.commons.security.user.service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heaven.jane.sourcegenerator.commons.security.authority.dao.AuthorityRepository;
import com.heaven.jane.sourcegenerator.commons.security.authority.dao.AuthoritySpec;
import com.heaven.jane.sourcegenerator.commons.security.authority.domain.Authority;
import com.heaven.jane.sourcegenerator.commons.security.user.dao.UserRepository;
import com.heaven.jane.sourcegenerator.commons.security.user.dao.UserSpec;
import com.heaven.jane.sourcegenerator.commons.security.user.domain.User;
import com.heaven.jane.sourcegenerator.commons.security.user.domain.UserVo;

/**
 * 用户业务类
 * @author heaven
 *
 */
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private UserRepository userRepository;

	@Autowired
	private AuthorityRepository authorityRepository;
	
	@Override
	public UserVo findUser(String name, String password) {
		Optional<User> condition = Optional.ofNullable(User.builder().username(name).password(password).build());
		Optional<User> user = userRepository.findOne(UserSpec.builder().condition(condition).build());
		UserVo target = new UserVo();
		BeanUtils.copyProperties(user.get(), target);
		return target;
	}

	@Override
	public UserVo findUserByToken(String token) {
		Optional<User> condition = Optional.ofNullable(User.builder().token(token).build());
		Optional<User> user = userRepository.findOne(UserSpec.builder().condition(condition).build());
		 List<Authority> roles = authorityRepository.findAll(
				AuthoritySpec.builder().userCondition(Optional.ofNullable(User.builder().id(user.get().getId()).build())).build());
		UserVo target = new UserVo();
		BeanUtils.copyProperties(user.get(), target);
		target.setRoles(roles.stream().map(role->role.getId()).collect(Collectors.toList()));
		return target;
	}
}
